#include "GameObject.h"

mtBEGIN(GameObject)
	mtBASE(ECS::Assembly);
	mtCONSTRUCTOR();
mtEND

#include <unordered_map>
#include "Components\Transform.h"
#include <string>

namespace impl
{
	typedef std::unordered_map<Identifier, GameObject*> ObjectMap;
	
	ObjectMap _objects;

	static size_t objCounter = 0;

	Identifier generateName()
	{
		std::string prefix = "GO";
		std::string name;

		do 
		{
			name = prefix;
			name += std::to_string(static_cast<long long>(objCounter));
			++objCounter;
		} 
		while (_objects.find(Identifier(name)) != _objects.end());

		return Identifier(name);
	}
}

GameObject::GameObject() :
	_name(impl::generateName())
{
	impl::_objects[_name] = this;
	createComponent<Transform>();
}

GameObject::~GameObject()
{
	impl::_objects.erase(_name);
}

const Identifier& GameObject::getName() const
{
	return _name;
}

void GameObject::setName( const Identifier& name )
{
	impl::_objects.erase(_name);
	_name = name;
	impl::_objects[_name] = this;
}

GameObject* GameObject::getObjectByName(const Identifier& name)
{
	auto it = impl::_objects.find(name);
	return (it != impl::_objects.end()) ? it->second : nullptr;
}

void GameObject::onDestroyed()
{
	impl::_objects.erase(_name);
}
